//
//  XGSelectedView.m
//  新闻
//
//  Created by 小果 on 16/3/30.
//  Copyright © 2016年 小果. All rights reserved.
//

#import "XGSelectedView.h"
#import "XGCategoryButton.h"

@interface XGSelectedView() <XGCategoryButtonDelegate>

@end
@implementation XGSelectedView

- (void)setIsModified:(BOOL)isModified
{
    // 无论什么状态，都需要修改所有按钮的状态
    for (XGCategoryButton *button in _buttonList) {
        if (isModified) {
            button.type = kNCButtonTypeMoveable;
            
            button.delegate = self;
        } else {
            button.type = kNCButtonTypeNormal;
            
            button.delegate = nil;
        }
    }
}

#pragma mark - 按钮的拖拽代理方法
- (void)categoryButtonIsMoving:(XGCategoryButton *)button
{
    NSLog(@"is moving %@", NSStringFromCGRect(button.frame));
    
    // 遍历按钮数组中的所有按钮
    // 检查与当前按钮的区域相交的情况
    // 如果，相交面积大于按钮面积的1/4， (w * h / 4）break
    // 取出了两个按钮，判断按钮的索引数值，根据索引数值递增，或者递减动画
    // 同时调整数据
    int exchangeIndex = -1;
    
    for (XGCategoryButton *b in _buttonList) {
        if (b != button) {
            CGRect interRect = CGRectIntersection(b.frame, button.frame);
            
            // 判断相交面积是否超过1/4
            if (interRect.size.width * interRect.size.height * 4 > b.frame.size.width * b.frame.size.height) {
                exchangeIndex = b.index;
                
                break;
            }
        }
    }
    
    if (exchangeIndex > 0 && exchangeIndex != button.index) {
        // 做交换处理
        if (exchangeIndex > button.index) {
            // 向前移动
            [self decreaseMoveFrom:exchangeIndex to:button.index];
        } else {
            // 向后移动
            [self increaseMoveFrom:exchangeIndex to:button.index];
        }
        
#warning 还需要对数组中的数据做一下处理！！！
        
        button.index = exchangeIndex;
        
        // 需要对数组进行重新的排序，更新数组的索引数值
        [_buttonList sortUsingComparator:^NSComparisonResult(XGCategoryButton *btn1, XGCategoryButton *btn2) {
            
            // 按照按钮的索引降序重新排列数组
            return btn1.index > btn2.index;
        }];
    }
}

- (void)categoryButtonDidMoved:(XGCategoryButton *)button
{
    NSLog(@"done");
}

#pragma mark - 私有成员方法
#pragma mark 向后移动
- (void)increaseMoveFrom:(NSInteger)from to:(NSInteger)to
{
    for (NSInteger i = from; i < to; i++) {
        XGCategoryButton *button = _buttonList[i];
        
        button.frame = [self rectForIndexOfButton:(i + 1)];
        
        button.index++;
    }
}

#pragma mark 向前移动
- (void)decreaseMoveFrom:(NSInteger)from to:(NSInteger)to
{
    // from 大于 to
    for (NSInteger i = (to + 1); i <= from; i++) {
        XGCategoryButton *button = _buttonList[i];
        
        // 计算-1的位置，设置按钮的位置
        button.frame = [self rectForIndexOfButton:(i - 1)];
        
        // 按钮的索引需要修改
        button.index--;
    }
}

@end
